package xsis.music.controller;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import xsis.music.model.AuthModel;
import xsis.music.model.UserModel;
import xsis.music.service.AuthService;
import xsis.music.service.UserService;

// Untuk random string
import static java.lang.Math.round;
import static java.lang.Math.random;
import static java.lang.Math.pow;
import static java.lang.Math.abs;
import static java.lang.Math.min;
import static org.apache.commons.lang3.StringUtils.leftPad;
/**
 Untuk Email
 */
import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

@Controller
public class StoreController {

	@Autowired
	private UserService userService;
	@Autowired
	private AuthService authService;

	@RequestMapping("/log")
	public String tampilLogin(HttpServletRequest req, HttpServletResponse res)
			throws IOException {

		return "login";
	}

	@RequestMapping(value = "/logfailure", method = RequestMethod.GET)
	public String printfailure(org.springframework.ui.ModelMap model) {
		model.addAttribute("error", "true");
		return "login";

	}

	@RequestMapping("/berhasil")
	public String berhasilLogin(HttpServletRequest req, HttpServletResponse res)
			throws IOException {

		return "Berhasil";
	}

	@RequestMapping("/reg")
	public String register(HttpServletRequest req, HttpServletResponse res)
			throws IOException {

		return "register";
	}
	
	@RequestMapping("/verify")
	public String verifikasi(HttpServletRequest req, HttpServletResponse res)
			throws IOException {

		return "verifikasi";
	}
	
	@RequestMapping("/Addver")
	public String Addverifikasi(@ModelAttribute UserModel User,HttpServletRequest req, HttpServletResponse res)
			throws IOException {

		String email = req.getParameter("email");
		String password = DigestUtils.md5Hex(req.getParameter("password"));
		String kode=req.getParameter("kode");
		User.setEmail(email);
		User.setPassword(password);
		User.setEnabled(1);
		User.setKode(kode);
		try {
			userService.updateAktifasi(User);
			res.sendRedirect("reg");
			
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}
	

	@RequestMapping(value = "/Addreg", method = RequestMethod.POST)
	public String Addregister(@ModelAttribute UserModel User,
			@ModelAttribute AuthModel Auth, HttpServletRequest req,
			HttpServletResponse res) throws IOException {

		String email = req.getParameter("email");
		String password = DigestUtils.md5Hex(req.getParameter("password"));
		String namaDepan = req.getParameter("namaDepan");
		String namaBelakang = req.getParameter("namaBelakang");
		String alamat = req.getParameter("alamat");
		String telp = req.getParameter("tlp");
		int enabled = Integer.parseInt(req.getParameter("enabled"));
		String auth = req.getParameter("authority");
		String kode=gen(10);
		
		User.setEmail(email);
		User.setPassword(password);
		User.setNama_dpn(namaDepan);
		User.setNama_blkng(namaBelakang);
		User.setAlamat(alamat);
		User.setNo_telp(telp);
		User.setEnabled(enabled);
		User.setKode(kode);
		Auth.setEmail(email);
		Auth.setAuthority(auth);
		try {
			userService.insert(User);
			authService.insert(Auth);
			res.sendRedirect("reg");
			kirimEmail(email,kode);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		return null;
	}

	public void kirimEmail(String email1, String kode) {
		final String username = "xsisonlineshopmusic@gmail.com";
		final String password = "bennayallaygan";

		Properties props = new Properties();
		props.put("mail.smtp.auth", "true");
		props.put("mail.smtp.starttls.enable", "true");
		props.put("mail.smtp.host", "smtp.gmail.com");
		props.put("mail.smtp.port", "587");

		Session session = Session.getInstance(props,
				new javax.mail.Authenticator() {
					protected PasswordAuthentication getPasswordAuthentication() {
						return new PasswordAuthentication(username, password);
					}
				});

		try {

			System.out.println(email1);
			Message message = new MimeMessage(session);
			message.setFrom(new InternetAddress(username));
			message.setRecipients(Message.RecipientType.TO,
					InternetAddress.parse(email1));
			message.setSubject("Testing Subject");
			message.setText("Kepada ,"
					+ email1
					+ "\n\n Masukkan Kode ini untuk verifikasi <strong>"+kode+"</strong> di sini http://localhost:8080/MusicStore/verify");

			Transport.send(message);

		} catch (MessagingException e) {
			throw new RuntimeException(e);
		}

	}

	public static String gen(int length) {
		StringBuffer sb = new StringBuffer();
		for (int i = length; i > 0; i -= 12) {
			int n = min(12, abs(i));
			sb.append(leftPad(Long.toString(round(random() * pow(36, n)), 36),
					n, '0'));
		}
		return sb.toString();
	}

}
